package com.zwz.crawler.basic;


import com.zwz.constant.Constant;
import com.zwz.parse.JsonParserUtil;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Connection;
import org.jsoup.Jsoup;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

import static com.zwz.constant.Constant.ENTERPRISE_ID;

/**
 * 联系人的信息获取
 */
@Slf4j
public class TungeeTopContacts {

    public static void startTungeeTopContacts(  ) throws UnsupportedEncodingException {
        // 构建请求参数
//        String enterpriseId = "577de19eadf21dc4";
        int takeCount = 5;

        // 编码参数
        String encodedEnterpriseId = URLEncoder.encode(ENTERPRISE_ID, "utf-8");
        String url = "https://sales.tungee.com/api/lead/contact/top-n-contacts"
                + "?enterprise_id=" + encodedEnterpriseId
                + "&take_count=" + takeCount;

        try {
            Connection.Response response = Jsoup.connect(url)
                    .method(Connection.Method.GET)
                    // 设置完整请求头（严格匹配浏览器格式）
                    .header("authority", "sales.tungee.com")
                    .header("accept", "*/*")
                    .header("accept-encoding", "gzip, deflate, br, zstd")
                    .header("accept-language", "zh-CN,zh;q=0.9")
                    .header("cache-control", "no-cache")
                    .header("pragma", "no-cache")
                    .header("priority", "u=1, i")
                    .header("referer", "https://sales.tungee.com/enterprise-details/577de19eadf21dc4/enterprise-information/basic-information")
                    .header("sec-ch-ua", "\"Not;A=Brand\";v=\"24\", \"Chromium\";v=\"128\"")
                    .header("sec-ch-ua-mobile", "?0")
                    .header("sec-ch-ua-platform", "\"Windows\"")
                    .header("sec-fetch-dest", "empty")
                    .header("sec-fetch-mode", "cors")
                    .header("sec-fetch-site", "same-origin")
                    .header("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36")
                    .header("x-tonxis-pid", "67864ea75f69e05d3b544ca7")
                    .header("x-tonxis-sid", "F0UwEUNiKGeGTqdfaeBdO1RMp4LWlJFkZWg/tJKfJ3SJ0e8=")
                    .header("x-tonxis-signature", "YTkOy4jVRXsVRXsV8hNJRXjJ8a148XMOE4MOMGc7FP2rFG8sRPjI8PF4E4trRhcw8G1sETChWIU2fNmdoyHm8o2p78nOYc8UL6NQYT.xkKvsw/n7OpYc/NXBhYNCUFUKY6mprVQwD8IDbrG2/zmeHDNXQNecLwsIvmz+LvYfNDQuKiJ+EP/7R/JCc1Oq9Wp+EksRTfpQ6tqDmwtOiRB797Ul2enH+vTbqM6QhjlKbHe6Q2R2xD+MFzbtvKTCVvWf2WwPUgRx5x33")
//                    .header("cookie", "")
                 //   .header("cookie", "tx_pid=67864ea75f69e05d3b544ca7; __wpkreporterwid_=cc4a07fc-7bb9-40a4-96bc-2cbac34b658f; __last_enter_version=sales; _co_i=6805a5576eceb9637696f09d; _tx_uid=680701dddca941522b77e864; _tx_cid=6805a5576eceb9637696f09d; DISTINCT_ID=b84fe276-099f-4932-92b3-d54b92ae384b; _tx_sid=MTc0NTMwMTE0MzYyMjo4MmQ2OTQ5MTY0NjU2ODNmYjQ5MjlmMjc3NDg5ZDFlZg==; Hm_lvt_f2ee75449fc055cc4dbceb4fe403bea3=1745301094,1745302709; HMACCOUNT=B4E402DF057C895E; SecurityCenterDuId=ImFBSG15RzdPdVdPdCtsWnNGMFVuSXhVPSI.GujnjA.YBo4Zvc8vs4jgEmtioacknOQ9pE; tg_referrer_source=https%3A%2F%2Fuser.tungee.com%2F; acw_tc=1a0c399c17453774119646163e0075ab798fc34903e67c7d6c26b928bcee49; Hm_lpvt_f2ee75449fc055cc4dbceb4fe403bea3=1745378947; accountCenterSessionId=.eJwlz0FOwzAQheG7eN3FjMex3eygqdjQZFOElE00tscyURSkJAUE4u4EOMD79b0vNYukYeU3GbbXIQVVZ55WOaj1JaladU0p7WfEvnnauqYv_Qmgu7bj4_P5o324bO14V12u_dQ2Z-rH-6IOavgbEpPPHjGAULKUMmZvUTBJkJAdOiH2UYcEho0YE2N0jglAA0c4AoDLnpL3htkguUCcuYrO6FgBcUimgoTBgvGgrcFkRIPOQns5OZIdEgvPs0w75l3CLywvshZVb8tt_3dbZfmnWg-ushCtRAlHS0EMotZaff8A6oBUfw.GunwBA._2rz4r41oANU7jlGOoxKODaYTDI; doncusSessionId=eyJfZnJlc2giOmZhbHNlLCJ1c2VyX2lkIjoiNjgwNzAxZGRkY2E5NDE1MjJiNzdlODY0In0.GunwDw.MS6NpEOd0M2gQRZTT-x6XZ4BdC4")
                    .header("cookie", Constant.cookies)
                    .ignoreContentType(true)
                    .ignoreHttpErrors(true)
                    .maxBodySize(0)
                    .timeout(30000)
                    .execute();

           log.info("HTTP状态码: " + response.statusCode());
//           //log.info("响应内容:\n" + response.body());
            handleErrorResponse(response);

            //解析
            JsonParserUtil.parseContact(response.body());


        } catch (IOException e) {
            System.err.println("请求异常: " + e.getMessage());
            e.printStackTrace();
        }
    }

    private static void handleErrorResponse(Connection.Response response) {
        switch (response.statusCode()) {
            case 401:
                System.err.println("[认证失败] 需要检查：");
                System.err.println("1. x-tonxis-signature 签名有效性（需动态生成）");
                System.err.println("2. x-tonxis-sid 参数时效性（通常为会话ID）");
                System.err.println("3. Cookie 中的 accountCenterSessionId 是否最新");
                break;

            case 403:
                System.err.println("[权限不足] 可能原因：");
                System.err.println("1. 当前账户无查看该企业联系人的权限");
                System.err.println("2. enterprise_id 不属于当前账户");
                break;

            case 429:
                System.err.println("[请求频繁] 解决方案：");
                System.err.println("1. 添加3-5秒随机请求间隔");
                System.err.println("2. 使用代理IP轮换策略");
                break;

            default:
                if (response.statusCode() != 200) {
                    System.err.println("未知错误码: " + response.statusCode());
                }
        }
    }

    // 如需生成动态签名可添加此方法（需逆向具体算法）
    private static String generateSignature(String enterpriseId, int takeCount) {
        // 示例伪代码：
        // String timestamp = String.valueOf(System.currentTimeMillis());
        // String rawData = enterpriseId + "|" + takeCount + "|" + timestamp;
        // return HmacUtils.hmacSha256Hex("secret_key", rawData);
        return "需根据实际加密规则生成";
    }
}
